<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Gallery/classes/PhpFox_ComponentBrowse.class.php, $Author:  $ */



/** Component for showing gallery pictures (main gallery page)
 *
 * @version $Id: PhpFox_ComponentBrowse.class.php 337 2008-02-17 13:36:37Z phpfoxsv $
 * @package module.gallery
 */
class PhpFox_Mod_Gallery_ComponentBrowse extends BaseComponent
{
    function process()
    {
        $oGalleryService = $this->_oModule->getService('Gallery');
        /* @var $oGalleryService PhpFox_Mod_Gallery_ServiceGallery */
        $oGalleryItem = $this->_oModule->getItem('Gallery');
        /* @var $oGalleryItem PhpFox_Mod_Gallery_ItemGallery */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oUrl = &App::getUrl();
        $oReq = &App::getRequest();
        $oTpl = $this->_oModule->getTemplate();
        App::loadClass('Pager');
        App::loadClass('Sorter');
        App::loadClass('Filter');
        if (App::getParam('bImageSecurity'))
		{
        	App::clearAccessForContent('gallery');
		}
        $aOut = array();

        $oSecurityService->checkPerm('gallery', array('read_only', 'full'));
        $oSecurityService->checkAccess('gallery');
        $bIsAdmin = $oSecurityService->isAdmin();
        $bIsStaff = $oSecurityService->isStaff(null, true);
        if ($bIsStaff && !$oSecurityService->hasStaffPerm('MENU_approve_pics'))
        {
            $bIsStaff = false;
        }
        if ($iId = $oReq->getInt('makefeature'))
        {
            if ($bIsAdmin || $bIsStaff)
            {
            	$oGalleryItem->load($iId);
            	$oGalleryItem->aData['feature'] = 1;
            	$oGalleryItem->update(array('feature'));
            }
            $oUrl->clearParams('makefeature');
            App::forward($oUrl->getUrl());
        }
        if ($iImageId = $oReq->getInt('delete'))
        {
            if ($bIsAdmin || $bIsStaff)
            {
                $oGalleryService->deleteItem($iImageId);
            }
            $oUrl->clearParams('delete');
            App::forward($oUrl->getUrl(), App::format('Mod_Gallery.info.image_deleted'), 'message', App::getPageName(), 'gallery');
        }
        if ($iId = $oReq->getInt('removefeature'))
        {
            if ($bIsAdmin || $bIsStaff)
            {
	            $oGalleryItem->load($iId);
	            $oGalleryItem->aData['feature'] = '';
	            $oGalleryItem->update(array('feature'));
            }
            $oUrl->clearParams('removefeature');
            App::forward($oUrl->getUrl());
        }
        $oUrl->setParam('display', $oReq->getInt('display', 1));
        $oUrl->setParam('mode', $oReq->getInt('mode', 1));
        $oUrl->setParam('pagesize', $oReq->getInt('pagesize', 12));
        $oUrl->setParam('field', $oReq->get('field'));
        $aForm             = array();
        $aForm['display']  = $oReq->getInt('display', 1);
        $aForm['mode']     = $oReq->getInt('mode', 1);
        $aForm['pagesize'] = $oReq->getInt('pagesize', 12);
        $aForm['field']    = $oReq->get('field', 'time');
        $aCategories = array();
        $aCategories[''] = App::format('option.select');

        foreach (App::getOptions('image_cat') as $sCategoryId => $sCategoryText)
        {
            $aCategories[$sCategoryId] = $sCategoryText;
        }
        $iPage = $oReq->get('page', 1);
        $aPagesizes = array(6, 12, 24);
        if (isset($aForm['pagesize']) && in_array($aForm['pagesize'], $aPagesizes))
        {
            $iPageSize = $aForm['pagesize'];
        }
        else
        {
            $iPageSize = 12;
            $aForm['pagesize'] = 12;
        }
        if (!isset($aForm['mode']) || ($aForm['mode'] != 2))
        {
            $aForm['mode'] = 1;
        }
        $aFields = array
        (
            'category' => array
            (
                'select' => $aCategories,
                'value'  => '=',
            ),
        );
        $oFilter = &new Filter('galbrowse', $aFields);
        $aSort = array
        (
            'time',
            'view',
            'rating',
        );
        $aDefSort = array($aForm['field'] => 'asc');
        $oSorter = &new Sorter($aSort, $aDefSort);

        $aTmp = $oFilter->aConditions;
        foreach ($aTmp as $sCond)
        {
        	$sCond = preg_replace('#{\#(.*)}#i', ' m.\\1', $sCond);
            $aCond[] = $sCond;
        }
        if ( eregi('featured', $oUrl->getUrl()) )
        {
        	$aCond[] = 'm.feature = 1';
        }

        if ( $tag = $oReq->get('tag') )
        {
        	$tag = str_replace("-", " ", $tag);
        	$oUrl->setParam('tag', strip_tags($tag));
        	$aCond[] = " m.tags LIKE '%". $this->oDatabase->escape($tag) ."%' ";
        }
        
        if ( $sSearchQuery = $oReq->get('search') )
        {
        	$oUrl->setParam('search', strip_tags($sSearchQuery));
			$aCond[] = " (m.text LIKE '%". $this->oDatabase->escape(strip_tags($sSearchQuery)) ."%' OR m.tags LIKE '%". $this->oDatabase->escape(strip_tags($sSearchQuery)) ."%') ";
        }        

		$sConditions = "";
		if ( isset($aCond) && count($aCond) > 0 )
		{
        	$sConditions = " AND " . implode(" AND ", $aCond);
        }

        $sSort = $oSorter->getOrder().(($oSorter->sSortField == 'rating') ? ', votes DESC' : '');

		$iCnt = $this->oDatabase->getField("SELECT COUNT(*) FROM ". App::getT('main') ." AS m
			WHERE m.allow = '' AND m.who_view = ''". $sConditions ."");

        $oPager = &new Pager($iCnt, $iPage, $iPageSize);
        $iFrom = $oPager->getOffset($iPage, $iPageSize);

		$aItems = $this->oDatabase->getRows("SELECT m.id, m.text, m.time, u.user, m.view, m.feature, m.comment FROM
			". App::getT('main') ." AS m
			LEFT JOIN ". App::getT('user') ." AS u ON(m.user_id = u.id)
			WHERE m.allow = '' AND m.who_view = ''". $sConditions ."
			ORDER BY ". $sSort ."
			LIMIT ". $iFrom .",". $iPageSize ."");

        foreach ($aItems as $iKey => $aItem)
        {
            $sImagePath = App::getParam('gallery.pic.path').'thumb/'.$aItem['id'].'.jpg';
            $aItems[$iKey]['imagesize'] = (file_exists($sImagePath)) ? filesize($sImagePath) : 0;
            $aItems[$iKey]['diff'] = floor((time() - $aItem['time']) / 86400);
        }

        $iTo = (($iFrom + $iPageSize) > $iCnt) ? $iCnt : ($iFrom + $iPageSize);
        $aFilterUrlParams = $aForm;
        $aFilterUrlParams['page'] = $iPage;

        $oTpl->assign(array(
            'aItems'           => $aItems,
            'iCnt'             => $iCnt,
            'iTo'              => $iTo,
            'iNewDays'         => App::getParam('public.gallery_new_days'),
            'iTopRating'       => App::getParam('public.gallery_top_rating'),
            'iFrom'            => ($iCnt) ? ($iFrom + 1) : 0,
        	'bAdmin'           => $bIsAdmin,
        	'bStaff'           => $bIsStaff,
        	'sMonthDateFormat' => App::getParam('format.monthdate%'),
            'aFilter'          => $oFilter->aHtml,
        	'sFilterName'      => 'galbrowse',
            'sImagePath'       => App::getParam('gallery.pic.url'),
            'aForm'            => $aForm,
            'sFilterUrl'       => App::makeUrl('public.gallery.main', $aFilterUrlParams),
            'sSort'            => $aForm['field'],
            'aPaging'          => ($iCnt) ? $oPager->getInfo($oUrl) : '',
        ));
        $aOut['main']   = $oTpl->fetch('Browse.html');
        $aOut['filter'] = $oTpl->fetch('GroupFilter.html');
        return $aOut;
    }
}
?>